package com.project.listener;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionLis implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session创建");
        //得到session会话对象
        HttpSession session = se.getSession();
        //得到上下文对象
       ServletContext context = session.getServletContext();
       //从上下文对象中取出在线人数
        int num = (Integer) context.getAttribute("onLine");
        //重新绑定在线人数
        context.setAttribute("onLine",num+1);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session销毁");
        //得到上下文对象
        ServletContext context = se.getSession().getServletContext();
        //取出在线人数
        int num = (Integer) context.getAttribute("onLine");
        //重新绑定在线人数
        context.setAttribute("onLine",num - 1);
    }
}
